// 柱状图组件
import * as echarts from 'echarts';
import { useEffect, useRef } from 'react';

const BarChart = ({ title, xData, yData }) => { 
  const chartRef = useRef(null);

  useEffect(() => {
    // 1.获取渲染图表的dom节点
    var chartDom = chartRef.current;
    if (!chartDom) return;
    
    // 2.初始化echarts实例
    var myChart = echarts.init(chartDom);
    
    // 3.准备图表参数
    var option = {
      title: {
        text: title,
        textStyle: {
          fontSize: 14,
          fontWeight: 'normal',
          color: '#666'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xData,
        axisLine: {
          lineStyle: {
            color: '#e8e8e8'
          }
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#666',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            color: '#f0f0f0'
          }
        }
      },
      series: [
        {
          data: yData,
          type: 'bar',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#1890ff' },
              { offset: 1, color: '#69c0ff' }
            ]),
            borderRadius: [4, 4, 0, 0]
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#40a9ff' },
                { offset: 1, color: '#91d5ff' }
              ])
            }
          }
        }
      ]
    };
    
    // 4.使用图表参数渲染图表
    option && myChart.setOption(option);
    
    // 响应式处理
    const handleResize = () => {
      myChart.resize();
    };
    
    window.addEventListener('resize', handleResize);
    
    // 清理函数
    return () => {
      window.removeEventListener('resize', handleResize);
      myChart.dispose();
    };
  }, [title, xData, yData]);

  return (
    <div 
      ref={chartRef} 
      style={{ 
        width: '100%', 
        height: '200px',
        minHeight: '200px'
      }}
    />
  );
};

export default BarChart;